package com.qwh.iapstm32;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Timer;

public class Fragment1 extends Fragment {
    TextView TextView_yali;

    static int kg;
    boolean commErr;
    MainActivity mainActivity;
    private String FileName;
    private byte bin[];
    TextView textView;
    StringBuffer stringBuffer;
    //    private Handler handler = new Handler();


    void update() { // 刷新msg的内容
        // Log.d("qwh", Integer.toString(mainActivity.rec_state));
        mainActivity.runOnUiThread(new Runnable() {
            public void run() {
                float yalif1 = mainActivity.yali1 * 3.3f / 4096 * 2;
                String yali1 = String.valueOf((double) (Math.round(yalif1 * 1000)) / 1000);
                float yalif2 = mainActivity.yali2 * 3.3f / 4096;
                String yali2 = String.valueOf((double) (Math.round(yalif2 * 1000)) / 1000);
                float yalif3 = mainActivity.yali3 * 3.3f / 4096;
                String yali3 = String.valueOf((double) (Math.round(yalif3 * 1000)) / 1000);
                float wdf = mainActivity.wd * 3.3f / 4096;
                double wdd = (1.43 - wdf) / 0.0043 + 25;
                String wd = String.valueOf((double) (Math.round(wdd * 1000)) / 1000);
                wd = fix3weixiaoshu(wd);
                TextView_yali.setText("程序文件扩展名以bin结尾\n" + "电压1:" + yali1 + "V\n电压2:" + yali2 + "V\n电压3:" + yali3 + "V\n内部温度:" + wd + "℃");

                Log.d("qwh", "二进制开关量:" + Integer.toBinaryString(kg));
                mainActivity.tvVoltameterValue.setText(String.valueOf((int) (kg / 2.55)));
                mainActivity.mBatteryView.setPower((int) (kg / 2.55));
                mainActivity.mBuffer = new byte[7];
                mainActivity.mBuffer[0] = 0x5A;
                mainActivity.mBuffer[1] = (byte) 0xA5;
                mainActivity.mBuffer[2] = 0x04;
                mainActivity.mBuffer[3] = 0x0A;
                mainActivity.mBuffer[4] = (byte) (kg >> 8);
                mainActivity.mBuffer[5] = (byte) kg;
                mainActivity.mBuffer[6] = 0x0A;

//            handler.postDelayed(this, 1000* 1);// 间隔1秒
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        kg = 0;
        mainActivity = (MainActivity) getActivity();
        mainActivity.setReciveOKListener(new MainActivity.ReciveOKListener() {
            @Override
            public void onReciveOKListener(final int position) {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView_yali.setText(String.valueOf(position));
                    }
                });
            }


        });
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView_yali = (TextView) (view.findViewById(R.id.TextView_yali));
        TextView_yali.setMovementMethod(ScrollingMovementMethod.getInstance());
        textView = view.findViewById(R.id.textView);
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());
        Button buttonOpen = (Button) view.findViewById(R.id.buttonOpen);
        buttonOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OpenFileDialog openFileDialog = new OpenFileDialog(mainActivity);
                openFileDialog.setOpenDialogListener(new OpenFileDialog.OpenDialogListener() {
                    @Override
                    public void OnSelectedFile(String fileName) {

                        FileName = fileName;
                        Log.d("qwh", FileName);
                        File file = new File(FileName);
                        bin = new byte[(int) file.length()];

                        try {
                            FileInputStream fileInputStream = new FileInputStream(file);
                            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                            bufferedInputStream.read(bin);

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Log.d("qwh", String.valueOf(bin.length));
                        textView.setText("");

                        textView.setText(bytesToHexString(bin));
                    }
                });
                openFileDialog.show();
            }
        });
        Button buttonDownload = (Button) view.findViewById(R.id.buttonDownload);
        buttonDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView_yali.setText("");
                commErr = false;
                if (bin != null) {
                    if (bin.length > 0 && bin.length < 0x18000) {
                        mainActivity.mBuffer = new byte[9];
                        mainActivity.mBuffer[0] = 0x5A;
                        mainActivity.mBuffer[1] = (byte) 0xA5;
                        mainActivity.mBuffer[2] = 0x06;
                        mainActivity.mBuffer[3] = (byte) 0xF0;
                        mainActivity.mBuffer[4] = (byte) (bin.length >> 24);
                        mainActivity.mBuffer[5] = (byte) (bin.length >> 16);
                        mainActivity.mBuffer[6] = (byte) (bin.length >> 8);
                        mainActivity.mBuffer[7] = (byte) bin.length;

                        mainActivity.mBuffer[8] = (byte) getXor(mainActivity.mBuffer);
                        mainActivity.rec_state = 0;
                        long startTime = System.nanoTime();  //開始時間

                        for (int i = 0; i < 10; i++) {
                            mainActivity.sendonce();
                            try {
                                for (int j = 0; j < 1000; j++) {
                                    Thread.sleep(1);
                                    if (mainActivity.rec_state == 0xF0) break;

                                }

                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if (mainActivity.rec_state == 0xF0) break;

                        }
                        if (mainActivity.rec_state == 0xF0) {
                            long consumingTime = System.nanoTime() - startTime; //消耗時間
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                            TextView_yali.append("擦除命令收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms");
                            mainActivity.rec_state = 0;

                        } else {
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("通讯失败！")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                            TextView_yali.append("擦除通讯失败！");
                            commErr = true;
                        }
                        for (int m = 0; m <=bin.length / 248; m++) {
                            mainActivity.mBuffer = new byte[257];
                            mainActivity.mBuffer[0] = 0x5A;
                            mainActivity.mBuffer[1] = (byte) 0xA5;
                            mainActivity.mBuffer[2] = (byte) 254;
                            mainActivity.mBuffer[3] = (byte) 0xF1;
                            mainActivity.mBuffer[4] = (byte) 0;
                            mainActivity.mBuffer[5] = (byte) 0;
                            mainActivity.mBuffer[6] = (byte) 0;
                            mainActivity.mBuffer[7] = (byte) m;
                            if (m == bin.length / 248)
                                System.arraycopy(bin, 248 * m, mainActivity.mBuffer, 8, bin.length - m * 248);
                            else {
                                System.arraycopy(bin, 248 * m, mainActivity.mBuffer, 8, 248);
                            }
                            mainActivity.mBuffer[256] = (byte) getXor(mainActivity.mBuffer);
                            mainActivity.rec_state = 0;
                            long startTime2 = System.nanoTime();  //開始時間

                            for (int i = 0; i < 10; i++) {
                                mainActivity.sendonce();
                                try {
                                    for (int j = 0; j < 1000; j++) {
                                        Thread.sleep(1);
                                        if (mainActivity.rec_state == 0xF1) break;

                                    }

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (mainActivity.rec_state == 0xF1) break;

                            }
                            if (mainActivity.rec_state == 0xF1) {
                                long consumingTime = System.nanoTime() - startTime2; //消耗時間
//                                new AlertDialog.Builder(view.getContext())
//                                        .setTitle("标题")
//                                        .setMessage(String.valueOf(m) + "收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms")
//                                        .setPositiveButton("确定", null)
//                                        .show();
                                TextView_yali.append("\n写偏移地址:248*" + String.valueOf(m) + " 收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms");
                                mainActivity.rec_state = 0;

                            } else {
//                                new AlertDialog.Builder(view.getContext())
//                                        .setTitle("标题")
//                                        .setMessage(String.valueOf(m) + "通讯失败！")
//                                        .setPositiveButton("确定", null)
//                                        .show();
                                TextView_yali.append("写FLASH缓存通讯失败！");
                                commErr = true;
                            }
                        }
                        if (commErr == false) {
                            mainActivity.mBuffer = new byte[9];
                            mainActivity.mBuffer[0] = 0x5A;
                            mainActivity.mBuffer[1] = (byte) 0xA5;
                            mainActivity.mBuffer[2] = 0x06;
                            mainActivity.mBuffer[3] = (byte) 0xF2;
                            mainActivity.mBuffer[4] = (byte) bin.length ;
                            mainActivity.mBuffer[5] = (byte) (bin.length >> 8);
                            mainActivity.mBuffer[6] = (byte) (bin.length >> 16);
                            mainActivity.mBuffer[7] =(byte) (bin.length >> 24);

                            mainActivity.mBuffer[8] = (byte) getXor(mainActivity.mBuffer);
                            mainActivity.rec_state = 0;
                            long startTime3 = System.nanoTime();  //開始時間

                            for (int i = 0; i < 10; i++) {
                                mainActivity.sendonce();
                                try {
                                    for (int j = 0; j < 1000; j++) {
                                        Thread.sleep(1);
                                        if (mainActivity.rec_state == 0xF2) break;

                                    }

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (mainActivity.rec_state == 0xF2) break;

                            }
                            if (mainActivity.rec_state == 0xF2) {
                                long consumingTime = System.nanoTime() - startTime3; //消耗時間
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                                TextView_yali.append("\n置更新标志命令收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms");
                                mainActivity.rec_state = 0;

                            } else {
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("通讯失败！")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                                TextView_yali.append("置更新标志通讯失败！");
                                commErr = true;
                            }
                        }
                        if (commErr == false) {
                            mainActivity.mBuffer = new byte[9];
                            mainActivity.mBuffer[0] = 0x5A;
                            mainActivity.mBuffer[1] = (byte) 0xA5;
                            mainActivity.mBuffer[2] = 0x06;
                            mainActivity.mBuffer[3] = (byte) 0xF3;
                            mainActivity.mBuffer[4] = 0 ;
                            mainActivity.mBuffer[5] = 0;
                            mainActivity.mBuffer[6] = 0;
                            mainActivity.mBuffer[7] =0;

                            mainActivity.mBuffer[8] = (byte) getXor(mainActivity.mBuffer);
                            mainActivity.rec_state = 0;
                            long startTime3 = System.nanoTime();  //開始時間

                            for (int i = 0; i < 10; i++) {
                                mainActivity.sendonce();
                                try {
                                    for (int j = 0; j < 1000; j++) {
                                        Thread.sleep(1);
                                        if (mainActivity.rec_state == 0xF3) break;

                                    }

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (mainActivity.rec_state == 0xF3) break;

                            }
                            if (mainActivity.rec_state == 0xF3) {
                                long consumingTime = System.nanoTime() - startTime3; //消耗時間
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                                TextView_yali.append("\n复位命令收到了,发送回传耗时：" + String.valueOf(consumingTime / 1000000.0) + " ms");
                                mainActivity.rec_state = 0;

                            } else {
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("标题")
//                                    .setMessage("通讯失败！")
//                                    .setPositiveButton("确定", null)
//                                    .show();
                                TextView_yali.append("复位命令通讯失败！");
                                commErr = true;
                            }
                        }
                    } else {
//                        new AlertDialog.Builder((view.getContext()))
//                                .setTitle("Title")
//                                .setMessage("程序文件超过0x30000大小,无法更新")
//                                .setPositiveButton("确定", null)
//                                .show();
                        TextView_yali.append("程序文件超过0x18000大小,无法更新");
                    }
                } else {
//                    new AlertDialog.Builder((view.getContext()))
//                            .setTitle("Title")
//                            .setMessage("请先打开程序文件(*.bin)")
//                            .setPositiveButton("确定", null)
//                            .show();
                    TextView_yali.append("请先打开程序文件(*.bin)");
                }
            }
        });


    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_main,
                container, false);
        return view;

    }

    @Override
    public void onStop() {
        super.onStop();
//        handler.removeCallbacks(runnable); // 停止刷新
    }

    @Override
    public void onResume() {
        super.onResume();
//        handler.postDelayed(runnable, 1000 * 1);

    }

    String fix3weixiaoshu(String s) {
        StringBuilder stringBuilder = new StringBuilder().append(s);
//        Log.d("qwh",String.valueOf(stringBuilder.indexOf(".")));
        if (stringBuilder.indexOf(".") == 2) {
            while (stringBuilder.length() < 6) {
                stringBuilder.append("0");
            }
        }
        if (stringBuilder.indexOf(".") == 1) {
            while (stringBuilder.length() < 5) {
                stringBuilder.append("0");
            }
        }
        return stringBuilder.toString();
    }

    /* Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)来转换成16进制字符串。
     * @param src byte[] data
     * @return hex string
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv + " ");
        }
        return stringBuilder.toString();
    }

    /**
     * Convert hex string to byte[]
     *
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    int getXor(byte shuzu[]) {
        int temp = 0;
        for (int i = 0; i < shuzu.length - 4; i++) {
            temp = temp ^ shuzu[i + 3];
        }
        return temp;
    }
}
